package com.hmdp.utils.interceptor;/**
 * ClassName:LoginInterceptor
 * Package:com.hmdp.utils.interceptor
 * Description:
 *
 * @Date:2022/3/23 20:53
 * @Author:lzp
 */

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:LoginInterceptor
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 因为上一个刷新拦截器已为我们获取到了token，现在只需要判断ThreadLocal中有无token即可
         */
        if(UserHolder.getUser() == null){
            // 没有，需要拦截，并设置状态码
            response.setStatus(401);// 401表示没有登录
            // 拦截
            return false;
        }
        // 有用户，则放行
        return true;
    }

    //业务完成后，销毁用户信息，避免用户内存泄露
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
